#include<iostream>
#include<string>
#include<cstring>
#include<cerrno>
#include<memory>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<netinet/in.h>
#include<ctype.h>
#include<fcntl.h>

class Sock
{
private:
    const static int gbacklog = 20;
public:
    Sock(){}
    static int Socket()
    {
        int listensock= socket(AF_INET,SOCK_STREAM,0);
        if(listensock < 0)
        {
            std::cerr<<"socket error"<<std::endl;
            exit(2);
        }
        int opt=1;
        setsockopt(listensock,SOL_SOCKET,SO_REUSEADDR|SO_REUSEPORT,&opt,sizeof(opt));
        return listensock;
    }
    static void Bind(int sock,uint16_t port,std::string ip="0.0.0.0")
    {
        struct sockaddr_in addr;
        memset(&addr,0,sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        inet_pton(AF_INET,ip.c_str(),&addr.sin_addr);
        if(bind(sock,(struct sockaddr*)&addr,sizeof(addr)) < 0)
        {
            std::cerr<<"bind error"<<std::endl;
            exit(3);
        }
    }
    static void Listen(int sock)
    {
        if(listen(sock,gbacklog) < 0)
        {
            std::cerr<<"listen error"<<std::endl;
            exit(4);
        }
    }
    static int Accept(int sock,std::string *ip,uint16_t *port,int *accept_errno)
    {
        struct sockaddr_in addr;
        socklen_t len = sizeof(addr);
        *accept_errno = 0;//初始化错误码
        int conn = accept(sock,(struct sockaddr*)&addr,&len);
        if(conn < 0)
        {
            *accept_errno = errno;
            return -1;
        }
        if(port)
        {
            *port = ntohs(addr.sin_port);
        }
        if(ip)
        {
            *ip= inet_ntoa(addr.sin_addr);
        }
        return conn;
    }
    static bool Connect(int sock,const std::string &ip,const uint16_t &port)
    {
        struct sockaddr_in addr;
        memset(&addr,0,sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(port);
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        if(connect(sock,(struct sockaddr*)&addr,sizeof(addr)) == 0)
            return true;
        else
            return false;
    }
    static bool SetNonBlock(int sock)
    {
        int flags = fcntl(sock,F_GETFL);
        if(flags < 0)
            return false;
        fcntl(sock,F_SETFL,flags|O_NONBLOCK);
        return true;
    }
    ~Sock(){}
};